/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.matching;

import mosdi.fa.SuffixOracle;
import mosdi.util.ArrayUtils;

public class BackwardOracleMatcher extends AbstractMatcher {
	
	/** Suffix automaton of reverse pattern. */
	private SuffixOracle oracle;
	
	public BackwardOracleMatcher(int alphabetSize, int[] pattern) {
		super(alphabetSize, pattern);
		this.pattern = pattern;
		this.oracle = new SuffixOracle(alphabetSize, ArrayUtils.reverseCopy(pattern));
	}

	protected WindowData processWindow(int[] text, int windowEndPos) {
		int cost = 0;
		int state = oracle.getStartState();
		int i = 0;
		for (; i<pattern.length; ++i) {
			cost += 1;
			state = oracle.getTransitionTarget(state, text[windowEndPos-i]);
			if (!oracle.mightBeFactor(state)) break;
		}
		return new WindowData(i==pattern.length, Math.max(1, pattern.length-i), cost);
	}

}
